package pipe

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

const (
	Connection = "HTTP/1.1 200 Connection established\r\n\r\n"
)

func dealHTTP(r *Request, data []byte) (result []byte, isHTTP bool) {
	result = data
	if list := strings.Split(string(data), " "); len(list) > 2 && strings.Contains(list[2], "HTTP") {
		if list[0] == http.MethodConnect {
			r.SetAddr(list[1])
			r.Write([]byte(Connection))
			isHTTP = true
		} else {
			u, err := url.Parse(list[1])
			if err == nil {
				port := u.Port()
				if len(port) == 0 {
					switch strings.ToLower(u.Scheme) {
					case "https":
						port = "443"
					default:
						port = "80"
					}
				}
				r.SetAddr(fmt.Sprintf("%s:%s", u.Hostname(), port))
				//result = []byte(strings.Replace(string(data), list[1], u.Path, 1))
			}
		}
	}
	return
}
